/**
 * Copyright (C), 2012-2018, 联奕科技有限公司
 * FileName: AsyncController
 * Author:   石贵武
 * Date:     2018\3\8 0008 9:27
 * Description: 异步处理
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package com.zhoudongxiu.web.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.async.DeferredResult;

import java.util.UUID;
import java.util.concurrent.Callable;

/**
 * 〈一句话功能简述〉<br> 
 * 〈异步处理〉
 *
 * @author 石贵武
 * @create 2018\3\8 0008
 * @since 1.0.0
 */
@RestController
@Slf4j
public class AsyncController {

    @Autowired
    private MockQueue mockQueue;

    @Autowired
    private DeferredResultHolder deferredResultHolder;

    @GetMapping("/order1")
    public Callable<String> order1() {

        log.info("主线程开始#####################");
        Callable<String> result = null;
        try {
            result = new Callable<String>() {

                @Override
                public String call() throws Exception {
                    log.info("副线程开始###############");
                    Thread.sleep(1000);
                    log.info("副线程结束###############");
                    return "success";
                }
            };
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("主线程返回####################");

        return result;
    }


    @GetMapping("/order2")
    public DeferredResult<String> order2() throws InterruptedException {
        log.info("主线程开始#####################");

        String orderId = UUID.randomUUID().toString();

        mockQueue.setPlaceOrder(orderId);

        DeferredResult<String> result = new DeferredResult<>();

        deferredResultHolder.getMap().put(orderId, result);


      //  Thread.sleep(1000);

        log.info("主线程返回####################");

        return result;
    }
}